﻿using FlyleafLib.MediaFramework.MediaPlaylist;
using Morin.Services;
using Morin.Shared.Models;
using Morin.Shared.Parameters;
using Morin.Wpf.Common;
using Morin.Wpf.ViewModels.Players;
using Stylet;
using StyletIoC;
using System.Reflection;
using System.Windows.Controls;

namespace Morin.Wpf.ViewModels.Television;

public class TelevisionViewModel(IAppService appService, IContainer container, IWindowManager windowManager) : Screen
{

    public string[]? TvGroupTitles { get; set; }
    private string? _tVGroupTitle;

    public string? TvGroupTitle
    {
        get => _tVGroupTitle;
        set
        {
            _tVGroupTitle = value;
            if (string.IsNullOrEmpty(value)) return;
            var model = _tvSources?.Find(x =>  x.GroupTitle.Equals(value));
            if (model == null) return;
            if (model.TvSourceDetails != null) TvSourceDetails = [.. model.TvSourceDetails];
            if (TvSourceDetails != null) Total = TvSourceDetails.Count;
        }
    }

    public int PageSize { get; set; } = 20;
    public int Total { get; set; }
    public int PageIndex { get; set; }

    private List<TvSourceModel>? _tvSources;
    public BindableCollection<TvSourceDetailModel>? TvSourceDetails { get; set; }
    public TvSourceModel? TvSourceDetailItem { get; set; }

    protected override void OnInitialActivate()
    {
        base.OnInitialActivate();

        _tvSources = appService.GetTvSources();

        if (_tvSources != null) TvGroupTitles = [.. _tvSources.Select(x => x.GroupTitle) ];
        if (TvGroupTitles is { Length: > 0 }) TvGroupTitle = TvGroupTitles[0];
    }

    private string GetEnumDescription(Enum enumObj)
    {
        var fieldInfo = enumObj.GetType().GetField(enumObj.ToString());
        if (fieldInfo != null)
        {
            object[] attribArray = fieldInfo.GetCustomAttributes(false);

            if (attribArray.Length == 0)
            {
                return enumObj.ToString();
            }
            else
            {
                if (attribArray[0] is System.ComponentModel.DescriptionAttribute attrib) return attrib.Description;
                return enumObj.ToString();
            }
        }

        return enumObj.ToString();
    }

    public void Play(TvSourceDetailModel o)
    {
        var playDict = new Dictionary<string, IEnumerable<VideoModel>>();
        var videoList = new List<VideoModel>();
        var model = new VideoModel { Episode = "1", VodPlayUrl = o.WebAddr };
        videoList.Add(model);

        var key = GetEnumDescription(o.NetworkCarrierType);
        playDict.Add(key, videoList);


        var viewModel = container.Get<PlayerViewModel>();
        viewModel.PlayMode = PlayMode.TV;
        viewModel.PlayDict = playDict;
        windowManager.ShowWindow(viewModel);
    }
}